package cn.itcast.bos.service.system.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.system.MenuDao;
import cn.itcast.bos.dao.system.PermissionDao;
import cn.itcast.bos.dao.system.RoleDao;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private PermissionDao permissionDao;
	
	@Autowired
	private MenuDao menuDao;

	/**
	  * @Description: 1、保存角色 2、角色关联菜单 3、角色关联权限
	  * @return 
	*/
	public void save(Role model,  String menuIds,Integer[] permissionIds) {
		roleDao.save(model);
		if(permissionIds!=null&&permissionIds.length>0){
			for (Integer permissionId : permissionIds) {
				Permission permission = permissionDao.findOne(permissionId);
				//角色关联权限     权限放弃维护
				model.getPermissions().add(permission);//向角色权限关系表T_Role_Permssion中添加记录
			}
		}
		
		if(StringUtils.isNotBlank(menuIds)){
			String[] split = menuIds.split(",");
			for (String menuId : split) {
				Menu menu = new Menu();    //瞬时态
				menu.setId(Integer.parseInt(menuId));   //托管态
				//角色关联菜单   菜单放弃维护   持久态对象关联脱管态对象
				model.getMenus().add(menu);//向角色权限关系表T_Role_Permssion中添加记录
			}
		}
		
	}

	
	
	//查询所有的角色数据
	public List<Role> findAll() {
		return roleDao.findAll();
	}



	@Override
	public Role findById(Integer id) {
		return roleDao.findOne(id);
	}



	@Override
	public void update(Role model, String menuIds, Integer[] permissionIds) {
		Role role=roleDao.findOne(model.getId());
		role.setName(model.getName());
		role.setKeyword(model.getKeyword());
		role.setDescription(model.getDescription());
		
		if(permissionIds!=null&&permissionIds.length>0){
			Set<Permission> newpSet = new HashSet<>();
			for (Integer permissionId : permissionIds) {
				Permission permission = permissionDao.findOne(permissionId);
				newpSet.add(permission);
			}
			role.setPermissions(newpSet);
		}
		
		if(StringUtils.isNotBlank(menuIds)){
			Set<Menu> newMenu = new HashSet<>();
			String[] split = menuIds.split(",");
			for (String menuId : split) {
				Menu menu = menuDao.findOne(Integer.parseInt(menuId));
				newMenu.add(menu);
			}
			role.setMenus(newMenu);
		}
	}
}
